package com.projectplace.GUI;


/*
 * Copyright (c) 2011 Projectplace International AB
 * Permission is hereby granted, free of charge, to any person 
 * obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, 
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:The above copyright notice and this 
 * permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.List;
import com.projectplace.R;
import com.projectplace.SingeltonPPClient;
import com.projectplace.GUI.adapter.Document_Comments_Adapter;
import com.projectplace.api.DocumentsApi;
import com.projectplace.api.objectResponses.DocumentsApi.DocumentComments;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class DocumentsView extends Activity {

	private final static String LOG_TAG = "DocumentsView";
	private ProgressDialog mProgressDialog;
	private int size;
	private String type;
	private String name;
	private String time;
	private String version;
	private String id;
	private TextView documentName;
	private TextView documentSize;
	private TextView documentModifiedTime;
	private TextView documentVersion;
	private Button open;
	private CheckBox saved;
	private static boolean buttonClick=false;
	private ListView list;
	private Activity mActivity;
	private static Handler hand;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.documentsdownload);
		
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.my_title);
		
		hand = new Handler();
		size = getIntent().getIntExtra("size", 0);
		type = getIntent().getStringExtra("type");
		name = getIntent().getStringExtra("name");
		time = getIntent().getStringExtra("time");
		version = getIntent().getStringExtra("version");
		id = getIntent().getStringExtra("id");
		
		documentName = (TextView) findViewById(R.id.DOCUMENT_NAME);
		documentSize = (TextView) findViewById(R.id.SIZE_OF_DOCUMENT);
		documentModifiedTime = (TextView) findViewById(R.id.MODIFIED_TIME);
		documentVersion = (TextView) findViewById(R.id.VERSION_OF_DOCUMENT);
		saved = (CheckBox) findViewById(R.id.saveDocument);
		open = (Button) findViewById(R.id.btn_openDocument);
		list = (ListView) findViewById(R.id.list_document);
		
		documentName.setText(name);
		documentSize.setText("Size: " + Double.valueOf(size) / 1000 +" Kb");
		
		mActivity = this;
		
		//Can't initiate Calendar so we get the instance
		Calendar cal = Calendar.getInstance();
		//Takes millisec and the answer from the apis is in sec so multiply by 1000
		cal.setTimeInMillis(1000*Long.valueOf(time));
		
		
		documentModifiedTime.setText(new StringBuilder()
				        // Month is 0 based so add 1
						.append(cal.get(Calendar.DAY_OF_MONTH)).append("/")
				        .append(cal.get(Calendar.MONTH) + 1).append("/")
				        .append(cal.get(Calendar.YEAR)).append(" ")
				        .append(pad(cal.get(Calendar.HOUR_OF_DAY))).append(":")
				        .append(pad(cal.get(Calendar.MINUTE))));
		
		//Hard coded since Boolean.parse could fail
		if(!version.equals("false"))
			documentVersion.setText("Version " +version);
		else
			documentVersion.setText("");
		
		
		open.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
			 openFile();
				
			}
		});
	
		if(mActivity.getFileStreamPath(id).exists()){
			saved.setChecked(true);
			saved.setText("Delete");
		}
		
		
		
		saved.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				buttonClick=false;
				if(!saved.isChecked()){
					saved.setText("Save");
					if(mActivity.deleteFile(id)){
						Toast.makeText(DocumentsView.this,
								name +" Deleted",
								Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(DocumentsView.this,
								"Could not find file with name " +name,
								Toast.LENGTH_SHORT).show();
					}
				}
				else{
					mProgressDialog = new ProgressDialog(DocumentsView.this);
					mProgressDialog.setMessage("Please wait while your document is downloaded...");
					mProgressDialog.setIndeterminate(false);
					mProgressDialog.setMax(100);
					mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					DownloadFile filed = new DownloadFile();
					filed.execute(id);
				}
			}
		});
	}
	
	public void onCommentClick(View v) {
		Log.d(LOG_TAG, "TIME TO COMMENT");
		// LayoutInflater factory = LayoutInflater.from(this);

		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText input = new EditText(this);
		input.setLines(3);
		input.setGravity(Gravity.TOP);
		alert.setView(input);
		alert.setTitle("Write comment");
		
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString().trim();
				DocumentsApi.postDocumentComments(SingeltonPPClient.getInstance(), id, value, hand, new com.projectplace.api.Callback.Callback.ResponceListenerPostDocumentComment() {
					
					public void SERVER_ERROR(Error err) {
						// TODO Auto-generated method stub
						
					}
					
					public void BAD_TOKEN_ERROR(Error err) {
						// TODO Auto-generated method stub
						
					}
					
					public void onReceive(String response) {
						// TODO Auto-generated method stub
						onResume();
					}
				});
				/*
				Toast.makeText(getApplicationContext(), value,
						Toast.LENGTH_SHORT).show();*/
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		alert.show();
	}
	
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		if(!saved.isChecked()){
			if(mActivity.getFileStreamPath(id).exists()){
				mActivity.deleteFile(id);
			}
		}
	}
	
	@Override
	public void onResume(){
		super.onResume();
		
		DocumentsApi.getDocumentComments(SingeltonPPClient.getInstance(), hand, id, new com.projectplace.api.Callback.Callback.ResponceListenerDocumentComments() {
			
			public void SERVER_ERROR(Error err) {
				// TODO Auto-generated method stub
				
			}
			
			public void BAD_TOKEN_ERROR(Error err) {
				// TODO Auto-generated method stub
				
			}
			
			public void onReceive(List<DocumentComments> documentComments) {
				// TODO Auto-generated method stub
				list.setAdapter(new Document_Comments_Adapter(mActivity, documentComments));
			}
		});
	}
	
	private void openFile(){
		if (mActivity.getFileStreamPath(id).exists()) {
			Uri path = Uri.fromFile(mActivity.getFileStreamPath(id));
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(path, type);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

			try {
				startActivity(intent);
			} catch (ActivityNotFoundException e) {
				Toast.makeText(DocumentsView.this,
						"No Application Available to View" +type,
						Toast.LENGTH_SHORT).show();
			}
		}else{
			buttonClick=true;
			mProgressDialog = new ProgressDialog(DocumentsView.this);
			mProgressDialog.setMessage("Please wait while your document is downloaded...");
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			DownloadFile filed = new DownloadFile();
			filed.execute(id);
		}
	}
	
	 private static String pad(int c) {
	        if (c >= 10)
	            return String.valueOf(c);
	        else
	            return "0" + String.valueOf(c);
	}

	//Method needed for back button in titlebar
	public void onClick(View v){
		finish();
	}
	
	private class DownloadFile extends AsyncTask<String, Integer, String> {
		
		
		@Override
		protected void onPreExecute(){
			mProgressDialog.show();
		}
		
		@Override
		protected String doInBackground(String... urlToDownload) {
			int count;
			String urltemp = "https://api.projectplace.com/1/document/"+urlToDownload[0];
			SingeltonPPClient.getInstance();
			urltemp = SingeltonPPClient.getInstance().signRequest(urltemp);
			try {
				URL url = new URL(urltemp);
				url.openConnection();
				
				// this will be useful so that you can show a tipical 0-100%
				// progress bar
				// downlod the file
				InputStream input = new BufferedInputStream(url.openStream());
				 
				OutputStream output = mActivity.openFileOutput(id, Context.MODE_WORLD_READABLE);
				byte data[] = new byte[1024];
				long total = 0;
				while ((count = input.read(data)) != -1) {
					total += count;
					// publishing the progress....
					publishProgress((int) (total * 100 / size));
					output.write(data, 0, count);
				}
				output.flush();
				output.close();
				input.close();
			} catch (Exception e) {
				Log.d(LOG_TAG, "Exception");
			}
			return null;
		}

		@Override
		public void onProgressUpdate(Integer... args) {
			// here you will have to update the progressbar
			// with something like
			mProgressDialog.setProgress(args[0]);
		} 
		
		@Override
		protected void onPostExecute(String result) {
			mProgressDialog.dismiss();
			if(saved.isChecked())
				saved.setText("Delete"); 
			
			if (mActivity.getFileStreamPath(id).exists() && buttonClick == true) {
				
				Uri path = Uri.fromFile(mActivity.getFileStreamPath(id));
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(path, type);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

				try {
					startActivity(intent);
				} catch (ActivityNotFoundException e) {
					Toast.makeText(DocumentsView.this,
							"No Application Available to View" +type,
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	} 
}
